package 二叉树;

public class LC_700二叉搜索树中的搜素 {
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
    public TreeNode searchBST(TreeNode root, int val) {
//        if(root==null||root.val==val) return root;
//        TreeNode result=null;
//        if(val>root.val) result=searchBST(root.right,val);
//        if(val<root.val) result=searchBST(root.left,val);
//        return result;
        //迭代法
        while(root!=null){
            if(val>root.val)
                root=root.right;
            else if(val<root.val)
                root=root.left;
            else
                return root;
        }
        return root;
    }
}
